// 配置
var tem_module = {}, vmMenu = null, tem_menu = [];
var id = {
    form: 'sys_menu_form',
    table: 'sys_menu_table',
    module: 'sys_auth_module_table',
    menu: 'sys_sub_menu_form',
    permission: 'sys_sub_menu_permission_form'
}
var sys_menu = {
    form: {
        id: id.form,
        form: [
            {code:1, type:'text', field:'name', title:'菜单名称', placeholder:'请输入菜单名称'},
            {code:1, type:'text', field:'icon', title:'图标', placeholder:'查看图标库 https://www.layui.com/doc/element/icon.html'},
            {code:1, type:'number', field:'orderNumber', title:'排序', placeholder:'数字越大越靠前'}
        ]
    },
    menu: {
        id: id.menu,
        form: [
            {code:1, type:'text', field:'name', title:'菜单名称', placeholder:'请输入菜单名称'},
            {code:1, type:'text', field:'url', title:'菜单路由', placeholder:'请输入菜单路由'},
            {code:1, type:'text', field:'path', title:'路由路径', placeholder:'请输入菜单路径'},
            {code:1, type:'number', field:'orderNumber', title:'排序', placeholder:'数字越大越靠前'}
        ]
    },
    permission: {
        id: id.permission,
        form: [
            {code:1, type:'text', field:'name', title:'权限名称', placeholder:'请输入权限名称'},
            {code:1, type:'text', field:'flag', title:'权限标识', placeholder:'请输入权限标识'},
            {code:2, title:'类型',items:[
                    {field:'type', value:'1', title:'顶部按钮', type:'radio'},
                    {field:'type', value:'2', title:'数据侧边按钮', type:'radio'},
                    {field:'type', value:'3', title:'数据权限', type:'radio'}
                ]},
            {code:1, type:'text', field:'event', title:'执行事件', placeholder:'可选参数(当类型为数据侧边按钮时必填)'},
            {code:1, type:'text', field:'color', title:'按钮颜色', placeholder:'可选参数'},
            {code:1, type:'number', field:'orderNumber', title:'排序', placeholder:'数字越大越靠前'}
        ]
    },
    table: {
        id: id.table,
        url: api.system.module.table,
        cols:[
            {type:'checkbox', fixed: 'left'},
            {field: 'name', title: '模块名称'},
            {field: 'code', title: '模块编码'},
            {field: 'status', title: '状态', minWidth: 120, templet:function (res) {
                    return res.status == 0 ? '停用' : '启用'
                }
            },
            {field: 'orderNumber', title: '排序', minWidth: 60,},
        ],
        info:{
            height: '280px',
            data: [
                {name:'name', title:'模块名称'},
                {name:'code', title:'模块编码'},
                {name:'status', title: '状态', templet:function (val) {
                        return val == 0 ? '停用' : '启用'
                    }
                },
                {name: 'orderNumber', title: '排序'},
                {name: 'comments', title: '备注'}
            ]
        }
    },
    module: {
        id: id.module,
        url: api.system.module,
        page: false,
        cols:[
            {field: 'name', title: '模块名称', align: 'center'}
        ],
        toolbar: '<div class="layui-btn-container">' +
            '<button class="layui-btn layui-btn-sm" lay-event="create">创建菜单</button>' +
            '</div>',
        bar: function(bar){
            switch (bar.event) {
                case 'create':
                    sys_menu_view.form();
                    break;
            }
        },
        done: function (res, curr, count) {
            tem_module = res.data;
        }
    }
}

// 初始化
initialize({
    title: '权限菜单管理',
    init: function () {
        soda.table.render(sys_menu.module);
        vmMenu = $('#' + id.table).vm({data:[], count: 0});

//      点击模块
        table.on('row('+id.module+')', function(obj){
            tem_module = obj.data;
            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
            opt.sub.get();

        });
        element.init();
    }
})

// 视图view
var sys_menu_view = {
    form: function (_data) {
        if(tem_module.id){
            let title = '<span style="color: red;">[' + tem_module.name + ']</span> 权限菜单管理';
            app.form({
                title: title,
                height: '300px',
                finish: function(){
                    opt.sub.get();
                },
                init: function () {
                    soda.form.render(sys_menu.form);
                    if(_data){
                        soda.form.set(id.form, _data);
                    }else{
                        soda.form.set(id.form, {sort:0});
                    }
                },
                opt: function () {
                    var form = soda.form.get(id.form);
                    var v = soda.form.verify(form, id.form, ['name'])
                    if(!v.check){
                        soda.tips.warning(v.message);
                        return false
                    }
                    form.moduleId = tem_module.id;

                    // 数据处理
                    if(form.id){
                        data.update(form);
                    }else{
                        data.create(form);
                    }
                }
            })
        }else{
            soda.tips.warning('请先选择一个模块')
        }
    },
    delete: function (_ids) {
        soda.tips.confirm({
            text: '确定要删除选中的数据吗?',
            confirm: function () {
                data.delete(_ids).done(function (d) {
                    soda.tips.ok(d.message);
                    opt.sub.get();
                });
            }
        });
    },
    sub: {
        form: function (_parent, _data) {
            let title = '<span style="color: red;">[' + _parent.name + ']</span> 权限功能管理';
            app.form({
                title: title,
                height: '360px',
                finish: function(){
                    opt.sub.get();
                },
                init: function () {
                    //console.log(_data)
                    soda.form.render(sys_menu.menu);
                    if(_data){
                        _data.sort = _data.orderNumber;
                        soda.form.set(id.menu, _data);
                    }else{
                        soda.form.set(id.menu, {sort:0});
                    }
                },
                opt: function () {
                    var form = soda.form.get(id.menu);
                    var v = soda.form.verify(form, id.menu, ['name', 'url', 'path'])
                    if(!v.check){
                        soda.tips.warning(v.message);
                        return false
                    }
                    form.moduleId = tem_module.id;
                    form.parentId = _parent.id;

                    //console.log(form);

                    // 数据处理
                    if(form.id){
                        data.update(form).done(function (d) {
                            soda.tips.ok(d.message)
                            app.finishForm();
                        })
                    }else{
                        data.create(form).done(function (d) {
                            soda.tips.ok(d.message)
                            app.finishForm();
                        })
                    }
                }
            })
        },
        delete: function (_ids) {
            soda.tips.confirm({
                text: '确定要删除这条权限数据吗?',
                confirm: function () {
                    data.delete(_ids);
                }
            });
        }
    },
    permission: {
        form: function (_menu_id, _data) {
            app.form({
                title: '权限配置管理',
                height: '450px',
                finish: function(){
                    opt.sub.get();
                },
                init: function () {
                    soda.form.render(sys_menu.permission);
                    if(_data){
                        soda.form.set(id.permission, _data);
                    }else{
                        soda.form.set(id.permission, {type: 1});
                    }
                },
                opt: function () {
                    var form = soda.form.get(id.permission);
                    var v = soda.form.verify(form, id.permission, ['name', 'flag'])
                    if(!v.check){
                        soda.tips.warning(v.message);
                        return false
                    }
                    form.parentId = _menu_id;
                    form.moduleId = tem_module.id;
                    form.isMenu = 1;
                    // 数据处理
                    if(form.id){
                        data.update(form);
                    }else{
                        data.create(form);
                    }
                }
            })
        },
        delete: function (_ids, _menu_id) {
            soda.tips.confirm({
                text: '确定要删除这条权限数据吗?',
                confirm: function () {
                    data.permission.delete(_ids);
                }
            });
        }
    }
}

// 业务business
var data = {
    create: function (_form) {
        var param = {
            url: api.system.auth,
            data: _form,
            callback: function (d) {
                app.finishForm();
            }
        }
        return soda.http.post(param);
    },
    update: function(_form){
        var param = {
            url: api.system.auth + '/' + _form.id,
            data: _form,
            callback: function (d) {
                app.finishForm();
            }
        }
        return soda.http.put(param);
    },
    delete: function (_id) {
        var param = {
            url: api.system.auth + '/' + _id,
            callback: function (d) {
                soda.tips.ok(d.message);
                opt.sub.get();
            }
        }
        return soda.http.delete(param);
    },
    get: function (_moduleId) {
        var param = {
            url: api.system.auth + '/' +_moduleId,
            tips: 0,
            isAll: true,
            callback: function (d) {
                vmMenu.set(d);
                element.init();
                tem_menu = d.data;
            }
        }
        return soda.http.get(param);
    },
    module: function () {
        var param = {
            url: api.system.module
        }
        return soda.http.get(param);
    },
    permission: {
        create: function (_form) {
            var param = {
                url: api.system.auth.create + '/permission',
                data: _form
            }
            return soda.http.post(param);
        },
        update: function (_form) {
            var param = {
                url: api.system.auth.update + _form.id,
                data: _form
            }
            return soda.http.post(param);
        },
        delete: function (_id) {
            var param = {
                url: api.system.auth + '/' + _id,
                callback: function () {
                    opt.sub.get();
                }
            }
            return soda.http.delete(param);
        }

    }
}

// 操作controller
var opt = {
    add: function () {
        sys_menu_view.form();
    },
    update: function () {
        let selected = soda.table.check(id.table);
        if(selected.data.length != 1){
            soda.tips.warning('请选择一条数据进行编辑(仅能选择一条数据)');
            return false;
        }
        let row = selected.data[0];
        sys_menu_view.form(row);
    },
    delete: function () {
        let selected = soda.table.check(id.table);
        if(selected.data.length == 0){
            soda.tips.warning('至少要选择一条数据操作');
            return false;
        }
        let ids = soda.json.getVal(selected.data)
        sys_menu_view.delete(ids);
    },
    sub: {
        get: function(){
            data.get(tem_module.id);
        },
        add: function (obj) {
            let menu_id = $(obj).attr('data-id');
            let opt_menu = soda.json.get(tem_menu, menu_id);
            sys_menu_view.sub.form(opt_menu);
        },
        update: function (obj) {
            let menu_id = $(obj).attr('data-id');
            let opt_menu = soda.json.get(tem_menu, menu_id);
            sys_menu_view.form(opt_menu);
        },
        delete: function (obj) {
            let menu_id = $(obj).attr('data-id');
            let opt_menu = soda.json.get(tem_menu, menu_id);
            let ids = [opt_menu.id];
            sys_menu_view.sub.delete(ids);
        }
    },
    menu: {
        update: function (obj) {
            let menu_id = $(obj).attr('data-id');
            let parent_id = $(obj).attr('data-parent');
            let opt_menu = soda.json.get(tem_menu, parent_id);
            let opt_menu_sub = soda.json.get(opt_menu.sub, menu_id);

            sys_menu_view.sub.form(opt_menu, opt_menu_sub);
        },
        delete: function (obj) {
            let id = [$(obj).attr('data-id')];
            sys_menu_view.sub.delete(id);
        }
    },
    permission: {
        add: function (_this) {
            let menu_id = $(_this).attr('data-id');
            sys_menu_view.permission.form(menu_id);
        },
        update: function (_this) {
            let id = $(_this).attr('data-id');
            let menu_id = $(_this).attr('data-parent');
            let permission = getPermission(id);
            sys_menu_view.permission.form(menu_id, permission);
        },
        delete: function (_this) {
            let id = $(_this).attr('data-id');
            let menu_id = $(_this).attr('data-parent');
            sys_menu_view.permission.delete([id], menu_id);
        }
    }
}

function getPermission(_id) {
    let permission = []
    $.each(tem_menu, function (i, obj) {
        let subMenus = obj['sub'];
        $.each(subMenus, function (j, sub) {
            let p = sub['permission'];
            permission = soda.array.coalition(permission, p);
        })
    })
    return soda.json.get(permission, _id);
}
function createPermission(_data) {
    var html = '';

    $.each(_data, function (i, data) {
        let btnCls = data.isButton == 1 ? '' : ' layui-btn-normal ';
        html += '<button class="layui-btn '+btnCls+'" style="margin-top: 3px;">' +
            '<span data-id="'+data.id+'" data-parent="'+data.menuId+'" onclick="opt.permission.update(this);">'+data.name+'</span>' +
            '<span data-id="'+data.id+'" data-parent="'+data.menuId+'" onclick="opt.permission.delete(this);" class="layui-badge layui-bg-gray">X</span>' +
            '</button>'
    })
    return html;
}
